﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using CommonLibrary.DB;

namespace ServiceApplication.Dao.Basic
{
    public class ConfigDao
    {
        public Boolean AddKey(String key, String value)
        {
            if (keyExist(key))
                return false;
            String sql = "INSERT INTO config ([Key],[Value]) values (@key, @value)";
            List<SqlParameter> parameterList = new List<SqlParameter>();
            parameterList.Add(new SqlParameter("@key", key));
            parameterList.Add(new SqlParameter("@value", value));

            DBExecuteUtil.executeSqlWithPar(sql, parameterList.ToArray());

            return true;
        }

        public Dictionary<String, String> GetConfigs()
        {
            String sql = "SELECT [Key], [Value] FROM config";
            var result = DBExecuteUtil.querySqlArray(sql);
            Dictionary<String, String> dicConfig = new Dictionary<string, string>();
            for (int i = 0; i < result.Length; i++)
            {
                dicConfig[result[i][0]] = result[i][1];
            }

            return dicConfig;
        }

        public String GetConfig(String key)
        {
            String sql = "SELECT [Key], [Value] FROM config WHERE [Key]=@key";
            List<SqlParameter> parameterList = new List<SqlParameter>();
            parameterList.Add(new SqlParameter("@key", key));

            return key;
        }

        public void ChangeValue(String key, String value)
        {
            String sql = "UPDATE config SET [Value]=@value WHERE [Key]=@key";
            List<SqlParameter> parameterList = new List<SqlParameter>();
            parameterList.Add(new SqlParameter("@key", key));
            parameterList.Add(new SqlParameter("@value", value));

            DBExecuteUtil.executeSqlWithPar(sql, parameterList.ToArray());
        }

        private Boolean keyExist(String key)
        {
            String sql = "SELECT [Key] FROM config WHERE [Key]=@key";
            List<SqlParameter> paramterList = new List<SqlParameter>();
            paramterList.Add(new SqlParameter("@key", key));
            var result = DBExecuteUtil.queryDataList(sql, paramterList.ToArray());
            return result.Count > 0;
        }
    }
}
